package 抽象数据类型.LRU缓存;

import 抽象数据类型.DoubleNode;

/**
 * @description:
 * @author: ywk
 * @date: 2020-12-28
 */
public class DoubleList {
    private int length;
    private DoubleNode first;
    private DoubleNode last;

    // 在链表头部添加节点 x，时间 O(1)
    public void addFirst(DoubleNode node) {
        if (first == null || last == null) {
            first = last = node;
            return;
        }
        if (node == first) {
            return;
        }
        //删除该结点
        if (node.prev != null) {
            node.prev.next = node.next;
        }
        if (node.next != null) {
            node.next.prev = node.prev;
        }
        if (node == last) {
            last = last.prev;
        }
        node.next = first;
        first.prev = node;
        first = node;
        node.prev = null;
        last.next = null;
        length++;
    }

    // 删除链表中的 x 节点（x ⼀定存在）
    // 由于是双链表且给的是⽬标 Node 节点，时间 O(1)
    public void remove(DoubleNode node) {
        if (node == first) {
            first = first.next;
        }
        if (node == last) {
            last = last.prev;
        }
        if (node.prev != null) {
            node.prev.next = node.next;
        }
        if (node.next != null) {
            node.next.prev = node.prev;
        }
        length--;

    }

    // 删除链表中最后⼀个节点，并返回该节点，时间 O(1)
    public DoubleNode removeLast() {
        DoubleNode temp = last;
        last = last.prev;
        length--;
        return temp;
    }

    // 返回链表⻓度，时间 O(1)
    public int size(){
        return length;
    }
}
